const gulp           = require('gulp')
    , path           = require('path')
    , bower          = require('bower')
    , sh             = require('shelljs')
    , wiredep        = require('wiredep')
    , gutil          = require('gulp-util')
    , print          = require('gulp-print')
    , inject         = require('gulp-inject')
    , rename         = require('gulp-rename')
    , browserSync    = require('browser-sync')
    , browserSyncSpa = require('browser-sync-spa')
    ;

const PATHS = {
    SRC: path.join(__dirname, 'www')
};

browserSync.use(browserSyncSpa({
    selector: '[ng-app]'
}));

gulp.task('inject', function () {

    return gulp.src(path.join(PATHS.SRC, 'source.html'))
        .pipe(inject(gulp.src([
            path.join(PATHS.SRC, 'js/**/*.js'),
            path.join(PATHS.SRC, 'view/**/*.js')
        ], {read: false}), {relative: true}))
        .pipe(inject(gulp.src([
            path.join(PATHS.SRC, 'css/**/*.css')
        ], {read: false}), {relative: true}))
        .pipe(wiredep.stream())
        .pipe(rename('index.html'))
        .pipe(gulp.dest(PATHS.SRC));
});

gulp.task('inject-reload', ['inject'], function () {
    browserSync.reload();
});

gulp.task('watch', ['inject'], function () {

    // html
    gulp.watch([path.join(PATHS.SRC, '/source.html'), path.join(PATHS.SRC, '/view/**/*.html')], ['inject-reload']);

    // js
    gulp.watch([path.join(PATHS.SRC, 'js/**/*.js'), path.join(PATHS.SRC, 'view/**/*.js')], function (event) {
        if (isOnlyChange(event)) {
            browserSync.reload(event.path);
        } else {
            gulp.start('inject-reload');
        }
    });

    // css
    gulp.watch(path.join(PATHS.SRC, 'css/**/*.css'), function (event) {
        if (isOnlyChange(event)) {
            gulp.src(event.path).pipe(browserSync.stream());
        } else {
            gulp.start('inject-reload');
        }
    });
});

gulp.task('server', ['watch'], function () {
    browserSyncInit(PATHS.SRC);
});

function isOnlyChange(event) {
    return event.type === 'changed';
}

function browserSyncInit(baseDir, browser) {
    browser = browser === undefined ? 'default' : browser;

    var routes = null;
    if (baseDir === PATHS.SRC || (Array.isArray(baseDir) && baseDir.indexOf(PATHS.SRC) !== -1)) {
        routes = {
            '/node_modules': 'node_modules'
        };
    }

    var server = {
        baseDir: baseDir,
        routes : routes
    };

    browserSync.instance = browserSync.init({
        startPath: '/',
        server   : server,
        browser  : browser,
        ghostMode: false
    });
}

gulp.task('install', ['git-check'], ()=> {
    return bower.commands.install()
        .on('log', function (data) {
            gutil.log('bower', gutil.colors.cyan(data.id), data.message);
        });
});

gulp.task('git-check', (done)=> {
    if (!sh.which('git')) {
        console.log(
            '  ' + gutil.colors.red('Git is not installed.'),
            '\n  Git, the version control system, is required to download Ionic.',
            '\n  Download git here:', gutil.colors.cyan('http://git-scm.com/downloads') + '.',
            '\n  Once git is installed, run \'' + gutil.colors.cyan('gulp install') + '\' again.'
        );
        process.exit(1);
    }
    done();
});

gulp.task('default', ()=> {
    console.log(gutil.colors.red('gulp default task'));
});
